//
//  DynamicViewController.m
//  ffmpeg_demo
//
//  Created by hxh on 2021/2/7.
//

#import "DynamicViewController.h"
#import "RPLaunchScreenViewController.h"
#import "DiscoverListViewController.h"
#import "NewsListViewController.h"
#import "DynamicModel.h"
@interface DynamicViewController ()
@property (nonatomic,strong)UIImageView *coverImgView;
@property (nonatomic,strong)UIImageView *flagImgView;
@property (nonatomic,strong)UIButton *coverBtn;
@property (nonatomic,strong)UIView *countDownView;
@property (nonatomic,strong)UILabel *countDownTimeLb;
@property (nonatomic,strong)UIButton *countDownBtn;
//@property (nonatomic,strong)dispatch_source_t timer;
@property (nonatomic,strong)CAGradientLayer *gradientLayer; /// 头部视图的渐变层
@property (nonatomic,strong)DynamicModel *currentModel;
@property (nonatomic,strong)NSTimer * timer;
@property (nonatomic,assign)NSInteger timeCount;


@end

@implementation DynamicViewController

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self loadDataSource];
    // Do any additional setup after loading the view.
}

- (void)setUI{
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.coverImgView = [[UIImageView alloc]init];
    self.coverImgView.contentMode = UIViewContentModeScaleAspectFill;
    self.coverImgView.layer.cornerRadius = YES;
    [self.view addSubview:self.coverImgView];
    
    self.coverBtn = [[UIButton alloc]init];
    [self.coverBtn addTarget:self action:@selector(tapMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.coverBtn];
    
    self.countDownView = [[UIImageView alloc]init];
    self.countDownView.layer.cornerRadius = 13;
    self.countDownView.layer.masksToBounds = YES;
    self.countDownView.backgroundColor = RGBA(0, 0, 0, 0.2);
    [self.view addSubview:self.countDownView];
    
    self.countDownTimeLb = [[UILabel alloc]init];
    self.countDownTimeLb.textColor = [UIColor whiteColor];
    self.countDownTimeLb.font = font(14);
    [self.countDownView addSubview:self.countDownTimeLb];
    
    self.flagImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"common_dynamic_tag"]];
    self.flagImgView.hidden = YES;
    [self.view addSubview:self.flagImgView];
    
    [self.coverImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    [self.coverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    [self.countDownView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(26);
        make.right.equalTo(self.view).offset(-16);
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + 8);
    }];
    
    [self.countDownTimeLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.countDownView);
        make.left.equalTo(self.countDownView).offset(12);
        make.right.equalTo(self.countDownView).offset(-12);
    }];
    [self.flagImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.countDownView);
        make.left.equalTo(self.view).offset(16);
    }];
    
    self.countDownBtn = [[UIButton alloc]init];
    [self.countDownBtn addTarget:self action:@selector(countDownMethod) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.countDownBtn];
    
    [self.countDownBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.countDownView);
    }];
    
    self.countDownView.hidden = YES;
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = CGRectMake(0, 0, kScreenW, 88);
    self.gradientLayer.endPoint = CGPointMake(0, 0);
    self.gradientLayer.startPoint = CGPointMake(0, 1);
    self.gradientLayer.colors = [NSArray arrayWithObjects:
    (id)[RGBA(0, 0, 0, 0.0) CGColor],
    (id)[RGBA(0, 0, 0, 0.3) CGColor],nil];
    [self.view.layer addSublayer:self.gradientLayer];
}

- (void)countDownMethod{
    if (self.timer != nil) {
        [self.timer invalidate];
        self.timer = nil;

    }
    [self setupTabberVC];
}


- (void)tapMethod{
    if (self.currentModel.type.intValue == 1) {
        
    }else{
        if (self.timer != nil) {
            [self.timer invalidate];
            self.timer = nil;
        }
        [self setupTabberVC];
        
        [[XHPushVCTool sharedXHPushVCTool]pushTargetVCWithUrl:self.currentModel.url paramUrl:@""];
    }
}

- (void)setupTabberVC{
    [[NSUserDefaults standardUserDefaults]setObject:@1 forKey:@"isFirst"];
    [[NSUserDefaults standardUserDefaults]synchronize];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSString *dateString = [[NSUserDefaults standardUserDefaults]objectForKey:@"isLoginTime"];
    NSDate *date = [formatter dateFromString:dateString];
    if (![date isToday]) {
        [MobClick event:@"user_day_status_not_login"];
    }
    [self saveLoginTime];
    
    
    DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
    NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
    [UIApplication sharedApplication].keyWindow.rootViewController = nav;
    
}

- (void)timerAction{
    self.timeCount++;
    
    if (self.currentModel.skip.intValue == 1) {
      self.countDownTimeLb.text = [NSString stringWithFormat:@"跳过  %lu",self.currentModel.displayDuration.intValue - self.timeCount];
    }else{
        self.countDownTimeLb.text = [NSString stringWithFormat:@"%lu  秒",self.currentModel.displayDuration.intValue - self.timeCount];
    }
    if (self.timeCount == self.currentModel.displayDuration.intValue) {
        
        [self.timer invalidate];
        self.timer = nil;

        [self setupNextViewController];
    }
}


- (void)setAutoTimer{
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
//    __block NSInteger time = self.currentModel.displayDuration.integerValue + 1;
//    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//    dispatch_source_set_timer(timer,DISPATCH_TIME_NOW,1.0*NSEC_PER_SEC, 0);
//    dispatch_source_set_event_handler(timer, ^{
//        if (time == 1) {
//            dispatch_source_cancel(timer);
//            dispatch_async(dispatch_get_main_queue(), ^{
//               //判断是否是第一次登陆
//                [self setupNextViewController];
//            });
//        }else{
//            dispatch_async(dispatch_get_main_queue(), ^{
//                if (self.currentModel.skip.intValue == 1) {
//                    self.countDownTimeLb.text = [NSString stringWithFormat:@"跳过  %lu",time];
//                }else{
//                    self.countDownTimeLb.text = [NSString stringWithFormat:@"%lu  秒",time];
//                }
//            });
//            time--;
//        }
//    });
//    dispatch_resume(timer);
//
//    self.timer = timer;
}



- (void)loadDataSource{
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(StartupGet) parames:nil success:^(id responseObj) {
        self.currentModel = [DynamicModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        if (self.currentModel == nil) {
            [self setupNextViewController];
        }else{
            self.countDownView.hidden = NO;
            self.flagImgView.hidden = NO;
            
            if (self.currentModel.skip.intValue == 0) {
                self.countDownBtn.userInteractionEnabled = NO;
                self.countDownTimeLb.text = [NSString stringWithFormat:@"%@  秒",self.currentModel.displayDuration];
            }else{
                self.countDownBtn.userInteractionEnabled = YES;
                self.countDownTimeLb.text = [NSString stringWithFormat:@"跳过  %@",self.currentModel.displayDuration];
            }
    
            [self.coverImgView sd_setImageWithURL:[NSURL URLWithString:self.currentModel.picture]];
            
            [self setAutoTimer];
        }
        
    } failure:^(id error) {
        [self setupNextViewController];
    }];
}

- (void)setupNextViewController{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    if ([RPAppManager isLogin]) {
        NSString *dateString = [[NSUserDefaults standardUserDefaults]objectForKey:@"isLoginTime"];
        NSDate *date = [formatter dateFromString:dateString];
        if (![date isToday]) {
            [MobClick event:@"user_day_status_login"];
        }
        [self saveLoginTime];
        DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
        NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
        [UIApplication sharedApplication].keyWindow.rootViewController = nav;
//        TabBarViewController *tabBarVC = [[TabBarViewController alloc]init];
//        [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVC;
    }else{
        if (![[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirst"]boolValue]) {
            [self saveLoginTime];
            RPLaunchScreenViewController *launchScreenVC = [[RPLaunchScreenViewController alloc]init];
            // 设置rootVC 根据是否用户登录还是游客模式
            [UIApplication sharedApplication].keyWindow.rootViewController = launchScreenVC;
        }else{
            NSString *dateString = [[NSUserDefaults standardUserDefaults]objectForKey:@"isLoginTime"];
            NSDate *date = [formatter dateFromString:dateString];
            if (![date isToday]) {
                [MobClick event:@"user_day_status_not_login"];
            }
            [self saveLoginTime];
            
            DiscoverListViewController *listVC = [[DiscoverListViewController alloc]init];
            NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:listVC];
            [UIApplication sharedApplication].keyWindow.rootViewController = nav;
            
//            TabBarViewController *tabBarVC = [[TabBarViewController alloc]init];
//            [UIApplication sharedApplication].keyWindow.rootViewController = tabBarVC;
        }
    }
}


- (void)saveLoginTime{
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date = [[NSDate alloc]init];
    NSString *dateString = [formatter stringFromDate:date];
    [[NSUserDefaults standardUserDefaults]setObject:dateString forKey:@"isLoginTime"];
    [[NSUserDefaults standardUserDefaults]synchronize];
}

@end
